package com.game.raceroom.player.contrl
{
 
	import com.util.MapUtil;
	import com.game.raceroom.Room;
	import com.game.raceroom.player.MapInfo;
	import com.game.raceroom.player.disp.MapDisplayer;
	import com.util.Base64;
	import mx.controls.Alert;
	import mx.core.UIComponent;
	public class MapContrl 
	{
		public var mapDisp:MapDisplayer;
		public var actorContrl:ActorContrl;
		public var mapInfo:MapInfo;
		public var room:Room;
		public function MapContrl(room:Room,bg:UIComponent,fg:UIComponent,mapInfo:MapInfo)
		{
			this.room=room;
			//super(gameCanvas);
			mapDisp=new MapDisplayer(bg,fg,this);
			this.mapInfo=mapInfo;
			initMap();
		}
        public function updateMap():void{
        	mapDisp.updateMap(actorContrl._viewx,actorContrl._viewy);
        }
		private function initMap():void{
			//mapInfo.tilekit=MapUtil.getTileKit(mapInfo.tileKitId);
			parseTileData(MapUtil.getMapXml(mapInfo.tileDataId));
			mapDisp.drawFirst(mapInfo);
			room.initMapOk();
		}
 

 
		private function parseTileData(map:XML):void{
			try {
			//	mapInfo.viewIdx = new Array;
				mapInfo.physIdx = new Array;
				// Convert the downlaoded text into an XML instance
		        mapInfo.firctCft=map.@firctCft;
			    mapInfo.width_in_tiles=map.@width;
			    mapInfo.height_in_tiles=map.@height;
			    mapInfo.tile_width=map.@tilewidth;
			    mapInfo.tile_height=map.@tileheight; 
			    mapInfo.map_width=mapInfo.width_in_tiles*mapInfo.tile_width;
			    mapInfo.map_height=mapInfo.height_in_tiles*mapInfo.tile_height;
			    
//				var viewLayer:XMLList = map.layer[0].data;
//                var i:int=0;
//                           var id:int;
//				for each ( var tile:XML in viewLayer.elements() ) {
//                   
//					id=(int)(tile.@["gid"]);
//					if(id>0){
//						id=id-1;
//					}
//					mapInfo.viewIdx.push(id);
//				}

			  mapInfo.physIdx = Base64.decodeTile(map.layer[0].data);
			  /*
              var id:int;
				var physLayer:XMLList = map.layer[0].data;
     			
				for each (var  tile:XML in physLayer.elements() ) {
					id=(int)(tile.@["gid"]);
//					if(id>0){
//						id=id-mapInfo.gride;
//					}
					mapInfo.physIdx.push(id);
				}*/
				map=null;

			} catch ( e:TypeError ) {
				Alert("Could not parse text into XML" );
				trace( "Could not parse text into XML" );
				trace(e.getStackTrace());
			}

		}
		public function destroy():void{
			mapDisp.destroy()
			mapDisp=null;
			mapInfo=null;
		}
	}
}